package com.ac.api.component.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ac.api.component.entity.CpLabel;
import com.ac.api.component.dao.CpLabelMapper;
import com.ac.api.component.service.CpLabelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ac.api.component.vo.CpLabelTree;
import com.ac.api.component.vo.CpLabelVo;
import com.ac.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author gjj
 * @since 2024-10-26
 */
@Service
public class CpLabelServiceImpl extends ServiceImpl<CpLabelMapper, CpLabel> implements CpLabelService {
    @Autowired
    private CpLabelMapper cpLabelMapper;

    /**
     * 获取子节点列表
     * @param tree
     * @param list
     * @return
     */
    public List<CpLabelTree> getChildrenList(CpLabelTree tree, List<CpLabelTree> list){
        List<CpLabelTree> children = list.stream().filter(item -> Objects.equals(item.getParentid(), tree.getId())).map(
                (item) -> {
                    item.setChildren(getChildrenList(item, list));
                    return item;
                }
        ).collect(Collectors.toList());
        return children;
    }


    @Override
    public CpLabelVo getLabelById(Integer id) {
        return cpLabelMapper.findLabelById(id);
    }

    @Override
    public List<CpLabel> list(CpLabel example) {
        return this.list(buildWrapper(example));
    }

    @Override
    public IPage<CpLabel> page(CpLabel example, IPage page) {
        return this.page(page,buildWrapper(example));
    }

    /**
     * 构建查询
     *
     * @param example
     * @return
     */
    private QueryWrapper<CpLabel> buildWrapper(CpLabel example) {
        QueryWrapper<CpLabel> wrapper     = new QueryWrapper<>();
        wrapper.lambda().eq(CpLabel::getState,"t");
        return wrapper;
    }

    @Override
    public Page<CpLabelVo> findByPage(CpLabelVo example, Page page) {
        page.setOptimizeCountSql(false);
        return page.setRecords(this.baseMapper.findByExample(buildCpLabelVoWrapper(example), page));
    }

    /**
     * 构建查询
     *
     * @param example
     * @return
     */
    private QueryWrapper<CpLabelVo> buildCpLabelVoWrapper(CpLabelVo example) {
        QueryWrapper<CpLabelVo> wrapper     = new QueryWrapper<>();
        wrapper.like(StringUtil.isNotBlank(example.getModuleName()),"module_name",example.getModuleName())
                .eq(example.getModuleid()!=null,"moduleid",example.getModuleid())
                .eq("state","t")
                .orderByDesc("createtime");
        return wrapper;
    }

}
